from django.conf import settings
from django.db import models

from utils.models import CoreModel
from utils.ssh import SSH
from system.settings.utils import AppSetting

table_prefix = settings.TABLE_PREFIX  # 数据库表名前缀


class Host(CoreModel):
    hostname = models.CharField(max_length=50)
    ip = models.CharField(max_length=64)
    port = models.IntegerField(default=22)
    username = models.CharField(max_length=50)
    pkey = models.TextField(null=True, blank=True)
    desc = models.CharField(max_length=255, null=True, blank=True)
    group = models.ForeignKey('Group', related_name='group', on_delete=models.CASCADE, default=None)

    @property
    def private_key(self):
        return self.pkey or AppSetting.get('private_key')

    def get_ssh(self, pkey=None):
        pkey = pkey or self.private_key
        return SSH(self.ip, self.port, self.username, pkey)

    class Meta:
        db_table = table_prefix + 'host'
        verbose_name = '主机管理'
        ordering = ['create_datetime']
        verbose_name_plural = verbose_name


class Group(CoreModel):
    name = models.CharField(max_length=20)
    parent = models.ForeignKey(to='self', to_field='id', on_delete=models.CASCADE, related_name='self_parent',
                               verbose_name='上级节点', null=True, blank=True)
    sort_id = models.IntegerField(default=0)

    class Meta:
        db_table = table_prefix + 'host_groups'
        verbose_name = '主机组管理'
        ordering = ('-sort_id',)
